<template>
  <div class="tinymce-editor">
    <editor v-model="myValue" :init="init" @onExecCommand="onExecCommand"></editor>
  </div>
</template>
<script>
  import Editor from "@tinymce/tinymce-vue";
  import {upload} from "@/api/system/oss";

  var cos;
  export default {
    name: "tinymce-editor",
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        default: ""
      }
    },
    data() {
      return {
        init: {
          language_url: "/tinymce/zh_CN.js", //public目录下
          language: "zh_CN",
          height: 500,
          plugins: "lists image media table paste link searchreplace anchor code preview pagebreak importcss",
          toolbar: "undo redo searchreplace |  formatselect pagebreak | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link anchor image media table | removeformat code preview", //工具栏展示项
          toolbar_drawer: false,
          image_advtab: true,
          object_resizing: false,
          paste_data_images: true,
          content_css: "/tinymce/article.css",
          images_upload_handler: (blobInfo, success, failure) => {
            this.uploadFile(blobInfo.blob()).then(fileUrl => success(fileUrl)).catch(err => failure(err))
          }
        },
        myValue: this.value,
        uploading: false
      };
    },
    mounted() {
      // console.log('tinymce-editor mounted:',this.value)
      tinymce.init({});
    },
    methods: {
      onExecCommand(e) {
        //console.log(e)
      },
      uploadFile(file) {
        this.uploading = true;
        return new Promise((resolve, reject) => {
          let form = new FormData();
          form.append('file', file)
          upload(form).then(response => {
            this.$emit('uploaded', response.data.url)
            resolve(response.data.url)
          }).finally(() => {
            this.uploading = false;
          });
        });
      }
    },
    watch: {
      value(newValue) {
        this.myValue = newValue;
      },
      myValue(newValue) {
        this.$emit("input", newValue);
      }
    }
  };
</script>
